<template>
  <!-- 劳务分包商人员管理 -->
  <base-breadcrumb>
    <!-- 基础信息 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="基础信息"></title-name>
        <custom-form :formList="projectForm" isValidate :form="form" editModel="V"></custom-form>
      </a-card>
      <!-- 管理岗 -->
      <a-card :bordered="false">
        <title-name title="管理岗"></title-name>
        <a-button class="mb12" type="primary" icon="plus" @click="handleManage(0, 0)">添加管理人员</a-button>
        <s-table bordered ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" :showPagination="false">
          <template slot="actions" slot-scope="text, record">
            <MoreButton v-if="record.statusCode == 1">
              <a @click="handleManage(0, 1, record)">修改</a>
              <a @click="handleRemove(record)">移除</a>
            </MoreButton>
          </template>
        </s-table>
      </a-card>
      <!-- 班组管理 -->
      <a-card :bordered="false" style="margin-bottom: 50px">
        <title-name title="班组管理"></title-name>
        <a-button class="mb12" type="primary" icon="plus" @click="handleManage(1, 0)">添加班组</a-button>
        <s-table bordered ref="tableGroup" size="default" rowKey="teamId" :columns="columnsGroup" :data="loadDataGroup" :showPagination="false">
          <template slot="manage" slot-scope="text, record">
            <template v-if="record.statusCode == 1">
              <a v-if="record.name" @click="handleManage(2, 1, record)">{{ record.name }}</a>
              <a v-else @click="handleManage(2, 0, record)">还未设置</a>
            </template>
            <span v-else>{{ record.name }}</span>
          </template>
          <template v-if="record.statusCode == 1" slot="actions" slot-scope="text, record">
            <a @click="handleManage(1, 1, record)">编辑</a>
          </template>
          <template v-if="record.statusCode == 1" slot="peopleManage" slot-scope="text, record">
            <a @click="handleMove(record)">人员管理</a>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <a-button type="primary" @click="handleActiveClose">关闭</a-button>
    </div>
    <!-- 表单弹窗 -->
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      editModel="E"
      :api="editModel == 0 || dialogType != 0 ? null : api"
      :form="forms"
      :forms.sync="forms"
      :headerTitle="[`管理人员${['添加', '修改'][editModel]}`, '班组设置', '班组长设置'][dialogType]"
      :width="1000"
      :formList="[manageForm, groupForm, groupForm][dialogType]"
      :rules="rules"
      @confirm="handleConfirm"
      @search="handleSearch"
    />
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import DialogForm from '@/components/DialogForm' // 表单弹窗
import SelectJobs from '@/components/Select/SelectJobs' // 表单弹窗
import { createValidator, idCard, isPhone, isName } from '@/utils/regExpression' // 正则校验
import { getPersonList, getSub, addSubManager, editSubManager, removeSubManager, getSubManage, getSubTeam, addSubTeam, editSubTeam, setSubTeamLeader } from '@/api/project/projects'

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 100,
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '姓名',
    dataIndex: 'name',
    ellipsis: true
  },
  {
    title: '岗位',
    dataIndex: 'postName',
    ellipsis: true
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    ellipsis: true
  },

  {
    title: '身份证号码',
    width: 230,
    dataIndex: 'idCard'
  },
  {
    title: '性别',
    width: 100,
    dataIndex: 'sexName'
  },
  {
    title: '状态',
    width: 100,
    dataIndex: 'statusName'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: 150,
    scopedSlots: { customRender: 'actions' }
  }
]
const columnsGroup = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 100,
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '班组名称',
    ellipsis: true,
    dataIndex: 'teamName'
  },
  {
    title: '班组长',
    dataIndex: 'name',
    scopedSlots: { customRender: 'manage' }
  },
  {
    title: '班组长电话',
    width: 150,
    dataIndex: 'phone'
  },
  {
    title: '班组人数',
    ellipsis: true,
    dataIndex: 'memberSize'
  },
  {
    title: '进场时间',
    dataIndex: 'enterDate'
  },
  {
    title: '出场时间',
    dataIndex: 'exitDate'
  },
  {
    title: '状态',
    width: 100,
    dataIndex: 'statusName'
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: 100,
    scopedSlots: { customRender: 'actions' }
  },
  {
    title: '人员管理',
    dataIndex: 'peopleManage',
    width: 100,
    scopedSlots: { customRender: 'peopleManage' }
  }
]
export default {
  extends: new BaseEditPage(),
  name: 'employeeManage',
  components: {
    STable,
    DialogForm
  },
  data() {
    return {
      columns, // 管理岗表头
      columnsGroup, // 班组管理表头
      searchLoading: false, // 身份证搜索loading
      loading: false, // 页面loading
      form: { branchCompanyNameProjectName: '' }, // 表单
      forms: {}, // 弹窗表单
      dialogType: 0, // 弹窗类型：0 管理人员；1 班组管理；2 班组长管理
      editModel: 0, // 弹窗操作类型：0 添加；1 编辑
      visible: false, // 弹窗显隐控件
      isExist: false, // 身份证人员是否已存在
      manageList: [], // 管理岗列表
      groupList: [], // 班组列表
      api: { getDetail: getSubManage },
      loadData: () => {
        return new Promise((resolve) => {
          resolve({
            data: this.manageList
          })
        })
      }, // 管理岗表格
      loadDataGroup: () => {
        return new Promise((resolve) => {
          resolve({
            data: this.groupList
          })
        })
      }, // 班组管理表格
      projectForm: [
        {
          keyName: 'branchCompanyNameProjectName',
          label: '所属单位'
        },
        // {
        //   keyName: 'branchCompanyName',
        //   label: '分公司',
        // },
        // {
        //   keyName: 'projectName',
        //   label: '项目',
        // },
        {
          keyName: 'subContractorName',
          label: '分包'
        }
      ], // 基础信息表单列表
      rules: {
        idCard: [{ required: true, validator: createValidator(idCard, '请输入正确的身份证号码', true), trigger: 'blur' }],
        name: [{ required: true, whitespace: true, message: '请输入正确的姓名', trigger: 'change' }],
        // name: [{ required: true,whitespace:true, validator: createValidator(isName, '请输入正确的姓名', true), trigger: 'change' }],
        teamName: [{ required: true, whitespace: true, message: '请输入正确的班组名称', trigger: 'change' }],
        // teamName: [{ required: true, validator: createValidator(isName, '请输入正确的班组名称', true), trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        postId: [{ required: true, message: '请选择岗位', trigger: 'change' }],
        statusCode: [{ required: true, message: '请选择当前状态', trigger: 'change' }],
        enterDate: [{ required: true, message: '请选择进场时间', trigger: 'change' }],
        exitDate: [{ required: true, message: '请输入出场时间', trigger: 'change' }]
      } // 表单校验
    }
  },
  computed: {
    // 管理人员表单列表
    manageForm() {
      return [
        {
          keyName: 'idCard',
          type: 'a-input-search',
          label: '身份证号码',
          disabled: this.editModel == 1,
          span: 12,
          attrs: {
            loading: this.searchLoading
          }
        },
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.isExist || this.editModel == 1,
          label: '姓名',
          span: 12
        },
        {
          keyName: 'sex',
          type: 'a-select',
          disabled: this.isExist || this.editModel == 1,
          label: '性别',
          span: 12,
          data: [
            {
              value: '0',
              label: '女'
            },
            {
              value: '1',
              label: '男'
            }
          ]
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          label: '手机号码',
          precision: 0,
          span: 12
        },
        {
          keyName: 'postId',
          type: SelectJobs,
          label: '岗位',
          span: 12,
          attrs: {
            attr: {
              orgId: this.projectOrgId
            }
          }
        },
        {
          keyName: 'statusCode',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '当前状态',
          data: [
            {
              label: '出场',
              value: '0'
            },
            {
              label: '进场',
              value: '1'
            }
          ],
          span: 12
        },
        {
          keyName: 'enterDate',
          type: 'a-date-picker',
          label: '进场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return (this.forms.exitDate && current && current > this.moment(this.forms.exitDate).startOf('day')) || (this.form.enterDate && current && current < this.moment(this.form.enterDate).startOf('day'))
            }
          }
        },
        {
          keyName: 'exitDate',
          type: 'a-date-picker',
          hidden: this.forms.statusCode == 1,
          label: '出场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return this.forms.enterDate && current && current < this.moment(this.forms.enterDate).endOf('day')
            }
          }
        }
      ]
    },
    // 班组管理表单列表
    groupForm() {
      return [
        {
          keyName: 'teamName',
          type: 'BaseInput',
          disabled: this.dialogType == 2, // 当是班组长表单时，禁用班组名称
          label: '班组名称',
          span: 12
        },
        {
          keyName: 'idCard',
          type: 'a-input-search',
          hidden: this.dialogType != 2,
          label: '身份证号码',
          span: 12,
          attrs: {
            loading: this.searchLoading
          }
        },
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.isExist,
          hidden: this.dialogType != 2,
          label: '姓名',
          span: 12
        },
        {
          keyName: 'sex',
          type: 'a-select',
          disabled: this.isExist,
          hidden: this.dialogType != 2,
          label: '性别',
          span: 12,
          data: [
            {
              value: '0',
              label: '女'
            },
            {
              value: '1',
              label: '男'
            }
          ]
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          hidden: this.dialogType != 2,
          label: '手机号码',
          precision: 0,
          span: 12
        },
        {
          keyName: 'enterDate',
          type: 'a-date-picker',
          label: '进场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return (this.forms.exitDate && current && current > this.moment(this.forms.exitDate).startOf('day')) || (this.form.enterDate && current && current < this.moment(this.form.enterDate).startOf('day'))
            }
          }
        },
        {
          keyName: 'statusCode',
          type: 'a-select',
          disabled: this.editModel == 0 || this.dialogType == 2,
          label: '当前状态',
          data: [
            {
              label: '出场',
              value: '0'
            },
            {
              label: '进场',
              value: '1'
            }
          ],
          span: 12
        },
        {
          keyName: 'exitDate',
          type: 'a-date-picker',
          hidden: this.forms.statusCode == 1,
          label: '出场时间',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return this.forms.enterDate && current && current < this.moment(this.forms.enterDate).endOf('day')
            }
          }
        }
      ]
    }
  },
  mounted() {
    // 设置基础信息
    this.loading = true
    this.init()
      .then((res) => {
        this.loading = false
        if (res.data) {
          this.form = res.data // 表单映射
          this.form.branchCompanyNameProjectName = this.form.branchCompanyName + '/' + this.form.projectName
          // {
          //   keyName: 'branchCompanyName',
          //   label: '分公司',
          // },
          // {
          //   keyName: 'projectName',
          //   label: '项目',
          // },
          this.manageList = res.data.subContractorManagers // 管理岗映射
          this.groupList = res.data.subContractorTeams // 班组映射
          this.$refs.table.refresh(true)
          this.$refs.tableGroup.refresh(true)
        }
      })
      .catch(() => {
        this.loading = false
      })
  },
  methods: {
    /**
     * 初始化
     */
    init() {
      return getSub({ id: this.id })
    },
    /**
     * 初始化管理岗
     */
    getManageList() {
      this.$refs.table.localLoading = true
      this.init()
        .then((res) => {
          this.$refs.table.localLoading = false
          if (res.data) {
            this.manageList = res.data.subContractorManagers // 管理岗映射
            this.$refs.table.refresh(true)
          }
        })
        .catch(() => {
          this.$refs.table.localLoading = false
        })
    },
    /**
     * 初始化班组
     */
    getGroupList() {
      this.$refs.tableGroup.localLoading = true
      this.init()
        .then((res) => {
          this.$refs.tableGroup.localLoading = false
          if (res.data) {
            this.groupList = res.data.subContractorTeams // 班组映射
            this.$refs.tableGroup.refresh(true)
          }
        })
        .catch(() => {
          this.$refs.tableGroup.localLoading = false
        })
    },
    /**
     * 添加或编辑操作；dialogType弹窗类型：0 管理人员；1 班组管理；2 班组长管理；type操作类型：type: 0 添加，1 编辑；record：编辑项
     */
    handleManage(dialogType, type, record) {
      this.dialogType = dialogType
      this.editModel = type
      this.forms = record ? this.$clone(record) : { statusCode: '1', enterDate: this.moment().format('YYYY-MM-DD') }
      // 班组长设置时添加参数mark
      if (dialogType == 2) {
        if (type == 0) {
          this.forms.statusCode = '1'
        } else {
          record.subContractorTeamLeader && Object.assign(this.forms, this.$clone(record).subContractorTeamLeader)
          this.$nextTick(() => {
            this.isExist = true
          })
        }
        this.forms.mark = type
      }
      this.visible = true
    },
    /**
     * 移除管理人员
     */
    handleRemove(e) {
      this.$confirm({
        title: '温馨提示',
        content: `确认移除${e.name}？`,
        onOk: () => {
          return removeSubManager({ id: e.id }).then(() => {
            this.$message.success('移除成功！')
            this.getManageList()
          })
        }
      })
    },
    /**
     * 根据身份证搜索人员
     */
    handleSearch() {
      let value = arguments[1] // 搜索值
      this.searchLoading = true
      this.$refs.dialogForm.$refs.ruleForm.validateField('idCard', (valid) => {
        if (!valid) {
          getPersonList({ idCard: value })
            .then((res) => {
              this.searchLoading = false
              if (res.data?.length > 0) {
                let datas = res.data[0]
                // 回显人员身份证信息
                this.$set(this.$refs.dialogForm.forms, 'name', datas.name)
                this.$set(this.$refs.dialogForm.forms, 'sex', datas.sex)
                this.$set(this.$refs.dialogForm.forms, 'phone', datas.phone)
                this.$set(this.$refs.dialogForm.forms, 'laborerId', datas.id)
                this.isExist = true
                this.$message.success('获取人员信息成功！')
              } else {
                this.$message.warning('人员基础库里无此人员！')
              }
            })
            .catch(() => {
              this.searchLoading = false
            })
        } else {
          this.searchLoading = false
        }
      })
    },
    /**
     * 提交表单
     */
    handleConfirm(e) {
      e.inAndOutId = this.form.inAndOutId
      e.projectId = this.form.projectId
      let api = [
        [addSubManager, editSubManager],
        [addSubTeam, editSubTeam],
        [setSubTeamLeader, setSubTeamLeader]
      ][this.dialogType][this.editModel]
      this.$refs.dialogForm.loading = true
      api(e)
        .then((res) => {
          this.$refs.dialogForm.loading = false
          if (res.data) {
            this.$message.success((this.dialogType != 2 ? ['添加', '修改'][this.editModel] : '设置') + '成功！')
            this.visible = false
            let init = [this.getManageList, this.getGroupList, this.getGroupList][[this.dialogType]] // 初始化列表
            // 重置操作列表
            init()
            // 若是管理岗提交操作，且操作人的身份证和班组长的身份证一致，那么班组长则会被移除，重置班组列表刷新班组长信息
            if (this.dialogType == 0 && this.groupList.some((item) => item.subContractorTeamLeader.idCard == e.idCard)) {
              this.getGroupList()
            }
            // 若是班组长提交操作，且设置的身份证和管理岗人员的身份证一致，那么此管理人员则会出场，重置管理岗列表
            if (this.dialogType == 2 && this.manageList.some((item) => item.idCard == e.idCard && item.statusCode == 1)) {
              this.getManageList()
            }
          }
        })
        .catch(() => {
          this.$refs.dialogForm.loading = false
        })
    },
    /**
     * 跳转人员管理
     */
    handleMove(e) {
      window.open(`/subcontractors/groupEmployeeManage?id=${e.teamId}&projectOrgId=${this.projectOrgId}`)
      // this.$router.push({
      //   path: '/subcontractors/groupEmployeeManage',
      //   query: {
      //     id: e.teamId,
      //     projectOrgId: this.projectOrgId,
      //   },
      // })
    }
  },
  watch: {
    // 关闭页面时重置身份证信息
    visible(e) {
      !e && (this.isExist = false)
    },
    // 重置身份证信息
    'forms.idCard'(e) {
      this.$refs.dialogForm.forms.name && this.$set(this.$refs.dialogForm.forms, 'name', '')
      this.$refs.dialogForm.forms.sex && this.$set(this.$refs.dialogForm.forms, 'sex', void 0)
      this.$refs.dialogForm.forms.phone && this.$set(this.$refs.dialogForm.forms, 'phone', '')
      if (this.isExist) {
        this.isExist = false
      }
    }
  }
}
</script>
